package com.wbao.dianniu.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;


public class QAInfoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {
    private Context mContext;
    private List<QaResponse> mList;
    private LayoutInflater mInflater;
    //是否有热门置顶显示
    private int topCounts = 0;
    private static final int TYPE_ITEM = 0;
    private static final int TYPE_FOOTER = 1;

    //上拉加载更多
    public static final int PULLUP_LOAD_MORE = 0;
    //正在加载中
    public static final int LOADING_MORE = 1;
    //没有加载更多 隐藏
    public static final int NO_LOAD_MORE = 2;
    //上拉加载更多状态-默认为0
    private int mLoadMoreStatus = 0;
    private OnItemClickListener onItemClickListener;


    public QAInfoAdapter(Context ctx) {
        mContext = ctx;
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mList = new ArrayList<QaResponse>();
    }

    public void updateHeadInfo(int accountId, String nickName, String headPic, Integer sex, String label) {
        if (null == mList || mList.size() == 0) {
            return;
        }
        boolean isExist = false;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).userInfo.accountId == accountId) {
                mList.get(i).userInfo.realName = nickName;
                mList.get(i).userInfo.headPic = headPic;
                mList.get(i).userInfo.sex = sex;
                mList.get(i).userInfo.label = label;
                isExist = true;
            }
        }
        if (isExist) {
            notifyDataSetChanged();
        }
    }

    public void updatePartner(int accountId, int partner) {
        if (null == mList || mList.size() == 0) {
            return;
        }
        boolean isExist = false;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).userInfo.accountId == accountId) {
                mList.get(i).userInfo.partner = partner;
                isExist = true;
            }
        }
        if (isExist) {
            notifyDataSetChanged();
        }

    }


    /**
     * 清空数据
     */
    public void cleanData() {
        if (null != mList) {
            mList.clear();
        }
        topCounts = 0;
    }

    /**
     * 向前追加数据
     *
     * @param list
     */
    public void addForwardList(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        if (0 == list.size()) {
            return;
        }
        // 第一步 先从list中去重掉mlist中的数据 第二歩 删除去重的数据  第三步 把list数据加到mlist最前面
        List<QaResponse> delList = new ArrayList<>();
        boolean isBreak = false;
        for (int i = 0; i < mList.size(); i++) {
            for (int j = list.size() - 1; j >= 0; j--) {
                if (mList.get(i).id < list.get(j).id) {
//                    Log.e("TAG", "跳出循环，content=" + mList.get(i).content);
                    isBreak = true;
                    break;
                } else if (mList.get(i).id == list.get(j).id) { // 发现id相同的数据
//                    Log.e("TAG", " 发现相同数据： id = " + list.get(j).id + " j=" + j);
                    delList.add(mList.get(i));
                    break;
                } else {
                    continue;
                }

            }
            if (isBreak) {
                break;
            }
        }
        // 删除重复的数据
        if (delList.size() > 0) {
            for (int i = 0; i < delList.size(); i++) {
                boolean ret = mList.remove(delList.get(i));
//                Log.e("TAG", " 删除重复的数据： id= " + delList.get(i).id + "  ret=" + ret);
            }
        }
        mList.addAll(0, list);
    }

    /**
     * 向后追加数据
     *
     * @param list
     */
    public void addBackwardList(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        for (int i = 0; i < list.size(); i++) {
            mList.add(list.get(i));
        }
    }

    public void setData(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        mList = list;
    }

    public List<QaResponse> getList() {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        return mList;
    }

    /**
     * 最后一条数据的ID，倒序排列，这条数据最老
     *
     * @return
     */
    public Integer getLastId() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        return mList.get(mList.size() - 1).id;
    }

    /**
     * 第一条数据的ID，倒序排列，这条数据最新
     *
     * @return
     */
    public Integer getFirstId() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        // 取出最进的不是刚果发的那条数据的ID
        int id = mList.get(0).id;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).isOwnSend == false) {
//                Log.e("TAG", "find own flag ：i=" + i + "  name:" + mList.get(i).userInfo.realName);
                id = mList.get(i).id;
                break;
            }
        }
        return id;
    }

    /**
     * 数据是否置顶显示处理方法，主要处理是否置顶文字的显示和置顶与非置顶之间的分割线显示
     */
   /* public void processList() {
        topCounts = 0;
        for (int i = 0; i < mList.size(); i++) {
            if (1 == mList.get(i).top) {
                topCounts++;
            }
        }
        if (topCounts > 0) {
            mList.get(0).isTopShow = 1;
            mList.get(topCounts - 1).isLineShow = 1;
        }
    }*/

    @Override
    public int getItemCount() {
        return mList.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {
            //最后一个item设置为footerView
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.qa_list_item, parent, false);
            return new ItemViewHolder(view);
        } else if (viewType == TYPE_FOOTER) {
            View itemView = mInflater.inflate(R.layout.load_more_footview_layout, parent, false);
            return new FooterViewHolder(itemView);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) {
            ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
            final QaResponse resp = mList.get(position);
            if (null != resp) {
                // 头像--名称--label sex partener addV 统一处理
                PictureDownloadUtils.displayHeadImage(mContext, itemViewHolder.userHolder.headIV, resp.userInfo.headPic);
                itemViewHolder.userHolder.nameTV.setText(resp.userInfo.realName == null ? "" : resp.userInfo.realName);
                itemViewHolder.userHolder.labelTV.setText(resp.userInfo.label == null ? "" : resp.userInfo.label);
                Utils.showSex(mContext, resp.userInfo.sex, itemViewHolder.userHolder.sexIV);
                Utils.showPartner(mContext, resp.userInfo.partner, itemViewHolder.userHolder.partnerIV);
                Utils.showAuth(resp.userInfo, itemViewHolder.userHolder.addV);

                itemViewHolder.contentTV.setEmojiText(resp.content, resp.noticeJson);
                if (1 == resp.advert) {
                    itemViewHolder.hotOrAdvertTV.setText(mContext.getResources().getString(R.string.advert));
                    itemViewHolder.hotOrAdvertTV.setVisibility(View.VISIBLE);
                } else {
                    itemViewHolder.hotOrAdvertTV.setVisibility(View.GONE);
                }
                // 删除按钮
                if (resp.accountId == GlobalContext.getAccountId()) {
                    itemViewHolder.deleteTV.setVisibility(View.VISIBLE);
                } else {
                    itemViewHolder.deleteTV.setVisibility(View.INVISIBLE);
                }
                //是否点赞
                if (0 == resp.isGood) {
                    Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_nor);
                    right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                    itemViewHolder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
                } else {
                    Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_sel);
                    right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                    itemViewHolder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
                }
                Utils.showPriseCounts(resp.goodCount, itemViewHolder.praiseTV);
                Utils.showPriseCounts(resp.answerCount, itemViewHolder.commentTV);

                //添加监听事件
                itemViewHolder.userHolder.headIV.setOnClickListener(this);
                itemViewHolder.userHolder.nameTV.setOnClickListener(this);
                itemViewHolder.contentTV.setOnClickListener(this);
                itemViewHolder.forwardTV.setOnClickListener(this);
                itemViewHolder.commentTV.setOnClickListener(this);
                itemViewHolder.praiseTV.setOnClickListener(this);
                itemViewHolder.deleteTV.setOnClickListener(this);
                itemViewHolder.allLayout.setOnClickListener(this);

                if (TextUtils.isEmpty(resp.questImgs)) {
                    itemViewHolder.gridview.setVisibility(View.GONE); // 没有图片资源就隐藏GridView
                } else {
                    itemViewHolder.gridview.setVisibility(View.VISIBLE);
                    Utils.showGridView(mContext, resp.questImgs, itemViewHolder.gridview, true, true);
                }
            }

            itemViewHolder.userHolder.headIV.setTag(R.id.user_head, position);
            itemViewHolder.userHolder.nameTV.setTag(R.id.user_name, position);
            itemViewHolder.contentTV.setTag(R.id.qa_content_tv, position);
            itemViewHolder.forwardTV.setTag(R.id.include_forward_tv, position);
            itemViewHolder.commentTV.setTag(R.id.include_answer_tv, position);
            itemViewHolder.praiseTV.setTag(R.id.include_praise_tv, position);
            itemViewHolder.deleteTV.setTag(R.id.include_delete_tv, resp.id);
            itemViewHolder.allLayout.setTag(R.id.qa_item_layout, position);

        } else if (holder instanceof FooterViewHolder) {
            FooterViewHolder footerViewHolder = (FooterViewHolder) holder;
            switch (mLoadMoreStatus) {
                case PULLUP_LOAD_MORE:
                    footerViewHolder.mPbLoad.setVisibility(View.GONE);
                    footerViewHolder.mTvLoadText.setText("上拉加载更多...");
                    footerViewHolder.mLoadLayout.setVisibility(View.VISIBLE);
                    break;
                case LOADING_MORE:
                    footerViewHolder.mPbLoad.setVisibility(View.VISIBLE);
                    footerViewHolder.mTvLoadText.setText("正在加载...");
                    footerViewHolder.mLoadLayout.setVisibility(View.VISIBLE);
                    break;
                case NO_LOAD_MORE:
                    //隐藏加载更多
                    if (mList.size() >= 10) {
                        footerViewHolder.mTvLoadText.setText("没有更多数据");
                        footerViewHolder.mPbLoad.setVisibility(View.GONE);
                        footerViewHolder.mLoadLayout.setVisibility(View.VISIBLE);
                    } else {
                        footerViewHolder.mLoadLayout.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }

        }
    }


    @Override
    public void onClick(View v) {
        if (null != onItemClickListener) {
            onItemClickListener.itemClick(v);
        }
    }


    public int addOneQuestData(QaResponse addData) {
        int index = 0;
        if (null != mList) {
            mList.add(topCounts, addData);
            notifyDataSetChanged();
            index = topCounts;
        }
        return index;
    }

    public void removeOneData(int id) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == id) {
                mList.remove(i);
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void priseNotify(int questId, int isGood, int goodCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).isGood = isGood;
                mList.get(i).goodCount = goodCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void replyNotify(int questId, int answerCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).answerCount = answerCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void visitorUpdate(int questId, int visitorCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).visitorCount = visitorCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 更新加载更多状态
     *
     * @param status
     */
    public void changeMoreStatus(int status) {
        mLoadMoreStatus = status;
        notifyDataSetChanged();
    }


    /**
     * 设置回调监听
     *
     * @param listener
     */
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    public interface OnItemClickListener {
        void itemClick(View view);
    }

    class ItemViewHolder extends RecyclerView.ViewHolder {
        private LinearLayout allLayout;
        UserInfoHolder userHolder;
        /**
         * 热门置顶
         */
        private TextView hotOrAdvertTV;
        /**
         * 内容
         */
        public SpanTextView contentTV;
        /**
         * 转发数
         */
        public TextView forwardTV;
        /**
         * 点赞数
         */
        public TextView praiseTV;
        /**
         * 回复数
         */
        public TextView commentTV;
        /**
         * 删除
         */
        public TextView deleteTV;
        /**
         * 浏览
         */
        public TextView visitorTV;
        /**
         * 图片显示
         */
        private CanDoBlankGridView gridview;

        public ItemViewHolder(View itemView) {
            super(itemView);
            userHolder = new UserInfoHolder();
            allLayout = itemView.findViewById(R.id.qa_item_layout);
            userHolder.headIV = itemView.findViewById(R.id.user_head);
            userHolder.nameTV = itemView.findViewById(R.id.user_name);
            userHolder.sexIV = itemView.findViewById(R.id.user_sex);
            userHolder.partnerIV = itemView.findViewById(R.id.user_partner);
            userHolder.labelTV = itemView.findViewById(R.id.user_label);
            userHolder.addV = itemView.findViewById(R.id.add_v_iv);
            hotOrAdvertTV = itemView.findViewById(R.id.hot_advert_flag);
            contentTV = itemView.findViewById(R.id.qa_content_tv);
            forwardTV = itemView.findViewById(R.id.include_forward_tv);
            praiseTV = itemView.findViewById(R.id.include_praise_tv);
            commentTV = itemView.findViewById(R.id.include_answer_tv);
            deleteTV = itemView.findViewById(R.id.include_delete_tv);
            gridview = itemView.findViewById(R.id.noScroollGridView);
        }
    }

    class FooterViewHolder extends RecyclerView.ViewHolder {
        ProgressBar mPbLoad;
        TextView mTvLoadText;
        LinearLayout mLoadLayout;

        public FooterViewHolder(View itemView) {
            super(itemView);
            mPbLoad = itemView.findViewById(R.id.pbLoad);
            mTvLoadText = itemView.findViewById(R.id.tvLoadText);
            mLoadLayout = itemView.findViewById(R.id.loadLayout);
        }
    }


}
